package com.example.learning.demo.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * ClassName Server
 * Description
 *
 * @author <a href="mailto:xuxb@zjport.gov.cn">xuxb</a>
 * @date 2021/5/29 21:27
 * @since 1.0
 */
public class Server {
    private static Selector selector;
    private static int read = 1;
    private static int write = 1;
    public static void main(String[] args) {
        try {
            selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(8000));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("Server开启 端口 8000，等待连接。。。。。。");
            while (true) {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    try {
                        if (selectionKey.isAcceptable()) {
                            ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                            SocketChannel socketChannel = channel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println("客户端连接成功");
                        }
                        if (!selectionKey.isValid()){
                            continue;
                        }
                        if (selectionKey.isReadable()) {
                            handlerRead(selectionKey);
                        }
                        if (selectionKey.isWritable()){
                            handlerWrite(selectionKey);
                        }
                    }catch (Exception e){
                        selectionKey.cancel();
                        e.printStackTrace();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void handlerRead(SelectionKey selectionKey){
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            channel.read(buffer);
            System.out.println("服务端接收到消息：" + new String(buffer.array())+read);
            channel.register(selector, SelectionKey.OP_WRITE);
            read++;
        }catch (IOException e){
            System.out.println(e.getMessage());
            selectionKey.cancel();
            try {
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    private static void handlerWrite(SelectionKey selectionKey){
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            buffer.put(("我是服务端，给你回消息了"+write).getBytes());
            buffer.flip();
            channel.write(buffer);
            buffer.clear();
            channel.register(selector, SelectionKey.OP_READ);
            write++;
        }catch (IOException e){
            System.out.println(e.getMessage());
            selectionKey.cancel();
            try {
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
